/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package roles;

import avenue.MyWindowEvent;
import java.awt.Color;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import model.DBManager;
import model.Module;
import model.RolePermission;
import model.UserRole;

/**
 *
 * @author MAGN
 */
public class EditModuleForm extends javax.swing.JFrame {

    /**
     * Creates new form EditModuleForm
     */
    public EditModuleForm() 
    {
        initComponents();
         getContentPane().setBackground(Color.white);
        //Στοιχιση στο κέντρο 24/2/2013
        setLocationRelativeTo(null);
    }
    
    
    private boolean intToBool(int i) { // Μέθοδος που μετατρέπει το 1 σε True όποιος άλλος αριθμός μας δίνει false
        return (i == 1); // Ean i=1 tote true
    }

    private int boolToInt(boolean b) { // μέθοδος που μετατρέπει ένα boolean σε integer
        return (b == true ? 1 : 0); // Ean b = true dinei 1 allios 0
    }
    
    
    public EditModuleForm(RolePermission rp,boolean New) 
    {   
        em = DBManager.em;
        rPerm = rp ;
        UserRole ur= rPerm.getRoleId(); 
        String RoleDescr=rp.getRoleId().getRoleName().toString();
        if ( !(em.getTransaction().isActive()) )//εαν δεν είναι ενεργή η εποικοινωνια του Entity Manager
        {  em.getTransaction().begin(); } //Τότε ξεκίνα την
        initComponents();
        
         getContentPane().setBackground(Color.lightGray);
        //Στοιχιση στο κέντρο 24/2/2013
        setLocationRelativeTo(null);
        
        if (New)// Ean dimiourgoume neo tote exoume true
            {

            Query modQuery = em.createNamedQuery("Module.findAll", Module.class);
            List<Module> modList = modQuery.getResultList(); //erotima pou pairnei thn lista me ta module
            Query uRolPerQuery = em.createQuery("select rp from RolePermission rp where rp.roleId=:roleId").setParameter("roleId", ur);
            List<RolePermission> rolPerList = uRolPerQuery.getResultList(); //erotima pou pairnei tin Lista me ta RolePerm tou userRole
            ArrayList<Module> ComboBoxLista = new ArrayList();   // Enas pinakas me ola ta module pou xrisimopoio sto combo box           
            rPerm.setCanCreate(1);// arxikes times
            rPerm.setCanDelete(1);// arxikes times
            rPerm.setCanRetrieve(1);// arxikes times
            rPerm.setCanUpdate(1);// arxikes times
            rPerm.setStationLevelAccess(1);// arxikes times
            for (RolePermission rp2 : rolPerList) // φτιάχνουμε μία λίστα με τα module που έχει το RolePer
            {
                    Module mod = rp2.getModuleId(); // πάρε το module του ρόλου
                    ComboBoxLista.add(mod); //και πρόσθεσε στην λίστα το  module
            }
            for (Module mdo: modList) //φτιάχνουμε μία λίστα με τα module που δεν υπάρχουν
             
            {  
               if (! ComboBoxLista.contains(mdo)) //ean den eiparxei stin lista
                {                
                  modListBox.addItem(mdo.getDescription().toString());// tote balto sto ComboBox
                }
            }
            jTextField1.setText(rPerm.getRoleId().getRoleName()); // setarei ta paideia tis formas
            jTextField1.setEditable(false);// kai to kano mi editable
            jCheckBox1.setSelected(intToBool(rPerm.getCanCreate()));// setarei ta paideia tis formas
            jCheckBox2.setSelected(intToBool(rPerm.getCanDelete()));// setarei ta paideia tis formas
            jCheckBox3.setSelected(intToBool(rPerm.getCanRetrieve()));// setarei ta paideia tis formas
            jCheckBox4.setSelected(intToBool(rPerm.getCanUpdate()));  // setarei ta paideia tis formas
            jCheckBox5.setSelected(intToBool(rPerm.getStationLevelAccess()));  // setarei ta paideia tis formas
        }
        else
        {   
            jTextField1.setText( RoleDescr  ); // setarei ta paideia tis formas
            jTextField1.setEditable(false);// kai to kano mi editable
            modListBox.addItem(rPerm.getModuleId().getDescription());//kanei epilogi pediou sto Combo box
            modListBox.setEditable(false);// kai to kano mi editable
            jCheckBox1.setSelected(intToBool(rPerm.getCanCreate()));// setarei ta paideia tis formas
            jCheckBox2.setSelected(intToBool(rPerm.getCanDelete()));// setarei ta paideia tis formas
            jCheckBox3.setSelected(intToBool(rPerm.getCanRetrieve()));// setarei ta paideia tis formas
            jCheckBox4.setSelected(intToBool(rPerm.getCanUpdate()));  // setarei ta paideia tis formas
            jCheckBox5.setSelected(intToBool(rPerm.getStationLevelAccess()));  // setarei ta paideia tis formas
        }
    }
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */

    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        rolePermission1 = new model.RolePermission();
        jLabel1 = new javax.swing.JLabel();
        jTextField1 = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        jCheckBox1 = new javax.swing.JCheckBox();
        jCheckBox2 = new javax.swing.JCheckBox();
        jCheckBox3 = new javax.swing.JCheckBox();
        jCheckBox4 = new javax.swing.JCheckBox();
        jCheckBox5 = new javax.swing.JCheckBox();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        modListBox = new javax.swing.JComboBox();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("TelePass Edit Module");

        jLabel1.setText("Όνομα Ρόλου :");

        jLabel2.setText("Module           :");

        jCheckBox1.setText("Can Create");
        jCheckBox1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jCheckBox1ActionPerformed(evt);
            }
        });

        jCheckBox2.setText("Can Delete");
        jCheckBox2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jCheckBox2ActionPerformed(evt);
            }
        });

        jCheckBox3.setText("Can Retrieve");

        jCheckBox4.setText("Can Update");

        jCheckBox5.setText("Station Level Access");

        jButton1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/cancel.gif"))); // NOI18N
        jButton1.setText("Ακυρο");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jButton2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/save.gif"))); // NOI18N
        jButton2.setText("Αποθηκευση");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        modListBox.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                modListBoxActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                            .addComponent(jLabel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(modListBox, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 295, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jCheckBox5, javax.swing.GroupLayout.PREFERRED_SIZE, 151, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                                .addComponent(jCheckBox1)
                                .addGap(18, 18, 18)
                                .addComponent(jCheckBox2)
                                .addGap(18, 18, 18)
                                .addComponent(jCheckBox3)))
                        .addGap(18, 18, 18)
                        .addComponent(jCheckBox4)
                        .addGap(0, 0, Short.MAX_VALUE))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 101, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 123, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(24, 24, 24)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(modListBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(35, 35, 35)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jCheckBox1)
                    .addComponent(jCheckBox2)
                    .addComponent(jCheckBox3)
                    .addComponent(jCheckBox4))
                .addGap(18, 18, 18)
                .addComponent(jCheckBox5)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 30, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton2)
                    .addComponent(jButton1))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jCheckBox1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jCheckBox1ActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_jCheckBox1ActionPerformed

    private void jCheckBox2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jCheckBox2ActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_jCheckBox2ActionPerformed

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        //ενέργεια που εκτελειτε οταν πατάμε αποθηκευση
        String SelComBox= (String) modListBox.getSelectedItem(); //pairno tin epilogi tou combobox
        Query findMod = em.createNamedQuery("Module.findByDescription",Module.class).setParameter("description", SelComBox);// βρίσκω το module βάση τηε περιγραφής που ειπάρχει στο ComboBox
        Module modId = (Module) findMod.getSingleResult();  // Brisko to Module     
        rPerm.setModuleId(modId); //kai to setaro sto RolePermission 
        String userRoleS=jTextField1.getText(); // pairno to UserRole san text
        Query findUser =  em.createNamedQuery("UserRole.findByRoleName", UserRole.class).setParameter("roleName", userRoleS);// Βρίσκω τον ρόλο βάση της περιγραφής του
        UserRole userRol = (UserRole) findUser.getSingleResult(); //brisko to UserRole
        rPerm.setRoleId(userRol); // kai to setaro sto RolePermission
        rPerm.setCanCreate(boolToInt(jCheckBox1.isSelected()));//σετάρο τις παραμέτρους
        rPerm.setCanDelete(boolToInt(jCheckBox2.isSelected()));//σετάρο τις παραμέτρους
        rPerm.setCanRetrieve(boolToInt(jCheckBox3.isSelected()));//σετάρο τις παραμέτρους
        rPerm.setCanUpdate(boolToInt(jCheckBox4.isSelected()));//σετάρο τις παραμέτρους
        rPerm.setStationLevelAccess(boolToInt(jCheckBox5.isSelected()));//σετάρο τις παραμέτρους

        //Καλούμε τον window listener ώστε να κάνει αποθήκευση και κάνουμε κλείσιμο της φόρμας
        MyWindowEvent we = new MyWindowEvent(this, WindowEvent.WINDOW_CLOSED, true);
        for (WindowListener l : this.getWindowListeners()) {
            l.windowClosed(we);
        }
        this.setVisible(false);
     

          // TODO add your handling code here:
    }//GEN-LAST:event_jButton2ActionPerformed

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
  //Ενέργεια που εκτελείτε όταν πατάμε άκυρο
        MyWindowEvent we = new MyWindowEvent(this, WindowEvent.WINDOW_CLOSED, false);
        for (WindowListener l : this.getWindowListeners()) {
            l.windowClosed(we);
        }
        this.setVisible(false);        // TODO add your handling code here:
    }//GEN-LAST:event_jButton1ActionPerformed

    private void modListBoxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_modListBoxActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_modListBoxActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(EditModuleForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(EditModuleForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(EditModuleForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(EditModuleForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new EditModuleForm().setVisible(true);
            }
        });
    }
    EntityManager em;
    RolePermission rPerm;

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JCheckBox jCheckBox1;
    private javax.swing.JCheckBox jCheckBox2;
    private javax.swing.JCheckBox jCheckBox3;
    private javax.swing.JCheckBox jCheckBox4;
    private javax.swing.JCheckBox jCheckBox5;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JTextField jTextField1;
    private javax.swing.JComboBox modListBox;
    private model.RolePermission rolePermission1;
    // End of variables declaration//GEN-END:variables
}
